<template>
  <div>
    <el-card style="width: 600px">
      <el-form :model="form" ref="formRef" label-width="80px" size="small">
        <div style="text-align: center; margin: 10px 0">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9999/file/upload_re"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </div>
        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.username" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item prop="realname" label="昵称">
          <el-input v-model="form.realname" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="phone" label="电话">
          <el-input v-model="form.phone" autocomplete="off" />
        </el-form-item>
      </el-form>

      <div style="text-align: center">
        <el-button type="primary" @click="save">确认修改</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>

import userApi from '@/api/userManage'

export default {
  // name: 'Person',
  data() {
    return {
      form: {},
      user: localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {} // 拿到储存在浏览器中的对象
    }
  },
  created() {
    this.getUser().then(res => {
      console.log(res)
      this.form = res
    })
  },
  methods: {
    async getUser() {
      return (await this.request.get('/user/username/' + this.user.username)).data
    },
    save() {
      // 先触发表单验证
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 然后提交请求给后台
          userApi.saveUser(this.form).then(response => {
            // 成功提示
            this.$message({
              message: response.message,
              type: 'success'
            })
            // 关闭对话框
            this.dialogFormVisible = false
            // 刷新表格
            // this.getUserList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleAvatarSuccess(res) {
      // res就是文件的路径
      this.form.avatar = res
    }
  }
}
</script>
<style>
.avatar-uploader {
  text-align: center;
  padding-bottom: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  line-height: 138px;
  text-align: center;
}
.avatar {
  width: 138px;
  height: 138px;
  display: block;
}
</style>
